<?php

/**
* 绑定微信帐号
*/
class mc_weixin_bind extends ms_base
{
	public $model = null;

	protected $data = array();
	protected $member = array();

	protected $mp_openid = '';
	protected $user_openid = '';
	protected $user_unionid = '';

	function __construct($mp_openid, $user_openid, $user_unionid = '')
	{
		parent::__construct();
		$this->model = $this->loader->model('weixin:member_bind');
		$this->read($mp_openid, $user_openid);
	}

	function read($mp_openid, $user_openid)
	{
		$this->mp_openid 	= _T($mp_openid);
		$this->user_openid 	= _T($user_openid);

		$this->data = $this->model->read_by_openid($mp_openid, $user_openid);

		if(!$this->data) return $this->add_error('微信帐号尚未绑定', -1);
		$this->user_unionid 	= $this->data['user_unionid'];

		
		$this->member = $this->loader->model(':member')->read($this->data['uid']);
		if(!$this->member) return $this->add_error('绑定账号已不存在', -2);

		return true;
	}

	function login()
	{
		$hash = $this->autologin_hash();
		return _G('user')->login->remember($hash);
	}

	function get_bind_data()
	{
		return $this->data;
	}

	function get_member_data()
	{
		return $this->member;
	}

	function bind_link()
	{
		if(!$this->mp_openid||!$this->user_openid) return false;
		$time = strtotime(date('Y-m-d'), $this->timestamp);
		$hash = authcode($this->mp_openid."\t".$this->user_openid."\t".$this->user_unionid, 'ENCODE');
		$sign = msm_weixin_member_bind::get_sign_hash($this->mp_openid, $this->user_openid, $time);
		return U("weixin/bind/hash/$hash/sign/$sign", true, 'normal');
	}

	function autologin_hash()
	{
		if(!$this->member) return false;
		$hash = create_formhash($this->member['uid'], $this->member['username'], $this->member['password']);
		return authcode($this->member['uid']."\t".md5($hash), 'ENCODE');
	}

	function unbind()
	{
		$this->model->unbind($this->mp_openid, $this->user_openid);//删除绑定记录
	}
}

/** end */